package br.ufal.ic.bean;

import br.ufal.ic.util.HibernateUtil;
import br.ufal.ic.user.User;
import java.io.Serializable;
import javax.faces.context.FacesContext;

/**
 *
 * @author Marcos Paulo
 */
public class LoginBean extends AbstractBean implements Serializable {

    public final static String FAILURE_LOGIN = "FAILURE_LOGIN";
    public final static String SUCCESS_LOGIN = "SUCCESS_LOGIN";

    private String nickName;
    private String password;
    private boolean loginOk;

    public LoginBean() {
        loginOk = false;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isLoginOk() {
        return loginOk;
    }

    public String validateLogin() {
        if(loginOk) {
            return SUCCESS_LOGIN;
        }

        HibernateUtil.beginTransaction();
        User user = getUserDAO().findByNickName(nickName);

        if (user == null || !user.getPassword().equals(password)) {
            return FAILURE_LOGIN;
        }

        loginOk = true;


        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().
                put("user", user);

        return SUCCESS_LOGIN;
    }
}
